#include "console.h"

#include <Core/logger/logger.h>
#include <helpers/connector.h>

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QStringList>

static QString host = "localhost";
static int port = 51999;

class ConsolePrivate
{
public:
    ConsolePrivate() {}
    ~ConsolePrivate() {}
    Opl::Helpers::Connector optra;
    bool wantsToQuit;
    bool SendCommand(const QString& command)
    {
        if (command.trimmed().compare(QLatin1String("quit")) == 0)
        {
            exit(EXIT_SUCCESS);
        }
        else
        {
            optra.Send(command);
            return true;
        }

        return false;
    }

    void Interactive()
    {
        QTextStream qin(stdin, QFile::ReadOnly);
        const char *qscript_prompt = "optra>";
        const char *prompt = qscript_prompt;

        QString code;

        forever
        {
            QString line;

            printf("%s", prompt);
            fflush(stdout);

            line = qin.readLine();
            if (line.isNull())
                break;

            code += line;
            code += QLatin1Char('\n');

            if (line.trimmed().isEmpty())
            {
                continue;

            } else if (!SendCommand(code))
            {
                exit(EXIT_FAILURE);
            } else {
                //sendcommand(code);
                // QScriptValue result = sendcommand(code);//, QLatin1String("typein"));

                code.clear();
                prompt = qscript_prompt;

                if (wantsToQuit)
                    break;
            }
        }
    }

};

Console::Console(QObject *parent) :
    QObject(parent), O_PRIVATE_CREATE(Console)
{
    O_D(Console);
    QObject::connect(&d->optra, &Opl::Helpers::Connector::error, [=]()
    {
        LI.Fatal() << "Unable to connect";
        exit(EXIT_FAILURE);

    });
}

Console::~Console()
{
    O_PRIVATE_DELETE;
}

void Console::Start()
{
    O_D(Console);
    Opl::Helpers::ConnectorSetup ss(host, port, 0);
    d->optra.Setup(ss);
    QObject::connect(&d->optra, &Opl::Helpers::Connector::connected, [=]()
    {
        //d->Interactive();
        d->optra.Send("aaaa12345");
    });

    d->optra.Start();
}
